package com.gjintel.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

/**
 * @description zip批量打包 
 * @author wwang 
 * @date 2016年9月10日
 */
public class BatchZipDownload{

	public BatchZipDownload() {
		super();
	}

	/**
	 * 压缩文件(Apache compress)
	 * @param files 要压缩的文件
	 * @param fileNameList 上传时的真实文件名集合(oldName)
	 * @param baseName
	 * @param zos 打包文件的OutputStream
	 */
	public static void zip(List<File> files, List<String> fileNameList, String baseName, ZipArchiveOutputStream zos) {
		if (files != null) {
			Map<String, File> map = new HashMap<String, File>();
			for (int i = 0; i < files.size(); i++) {
				list(files.get(i), fileNameList.get(i), null, map);
			}
			if (!map.isEmpty()) {
				try {
					ZipArchiveOutputStream zaos = zos;// new
														// ZipArchiveOutputStream(zos);
					for (Map.Entry<String, File> entry : map.entrySet()) {
						File file = entry.getValue();
						ZipArchiveEntry zae = new ZipArchiveEntry(file, entry.getKey());
						zaos.putArchiveEntry(zae);
						InputStream is = new FileInputStream(file);
						byte[] b = new byte[1024 * 5];
						int i = -1;
						while ((i = is.read(b)) != -1) {
							zaos.write(b, 0, i);
						}
						is.close();
						zaos.closeArchiveEntry();
					}
					zaos.finish();
					zaos.close();
				} catch (IOException ex) {
					System.err.println("------>打包失败！" + ex.getMessage());
				}
			}
		}
	}
	
	/**
	 * 处理文件名问题（判读是否有重名的文件）
	 * @param f 当前文件
	 * @param fileName 当前文件的服务器名称
	 * @param parent 父目录
	 * @param map key:当前文件的服务器名称 value: 文件File
	 * @param fileNameCollection 文件名集合
	 */
	private static void list(File f,String fileName, String parent, Map<String, File> map) {
		String name = fileName;
		//name = parent + "/" + name;// 设置在zip包里的相对路径
		File val = map.get(fileName);
		if(val!=null){//存在相同的文件名
			name=name.substring(0, name.lastIndexOf("."))+"_"//
					+System.currentTimeMillis()+"-"+(int)(Math.random()*100)//
					+name.substring(name.lastIndexOf("."),name.length());
		}
		map.put(name, f);
		
//		if (f.isFile()) {
//			map.put(name, f);
//		} else if (f.isDirectory()) {
//			for (File file : f.listFiles()) {
//				list(file, name, map);
//			}
//		}
	}
	
	
	
	
	
	//============================================================================
	
	
	/**
	 * 打包文件名集合（jdk 中文乱码）
	 */
	public static void zipFile(List<File> subsList,List<String> fileNameList ,String baseName, ZipOutputStream zos) throws IOException {
		List<String> fileNameCollection=new ArrayList<String>();
		for (int i = 0; i < subsList.size(); i++) {
			File f = subsList.get(i);
			String fileName="";
			//判读是否有改文件名
			if(!fileNameCollection.contains(fileNameList.get(i))){
				//将打包文件名加入集合中
				fileNameCollection.add(fileNameList.get(i));
				fileName=baseName + fileNameList.get(i);
			}else{//有相同的文件名
				fileName=baseName//
						+fileNameList.get(i).substring(0, fileNameList.get(i).lastIndexOf("."))+"_"//
						+System.currentTimeMillis()//
						+fileNameList.get(i).substring(fileNameList.get(i).lastIndexOf("."),fileNameList.get(i).length());
			}
			zos.putNextEntry(new ZipEntry(fileName));
			FileInputStream fis = new FileInputStream(f);
			byte[] buffer = new byte[1024];
			int r = 0;
			while ((r = fis.read(buffer)) != -1) {
				zos.write(buffer, 0, r);
			}
			fis.close();
		}
	}

	private String getZipFilename() {
		Date date = new Date();
		String s = date.getTime() + ".zip";
		return s;
	}

	
	/**
	 * @description 测试 
	 * @author wwang 
	 * @date 2016年9月13日
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
//		FileOutputStream outputStream = new FileOutputStream("g:/ww.zip");  
//		ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(outputStream));
//		//File[] files = new File[2];
//		//files[0] = new File("g:/w.png");
//		//files[1] = new File("g:/ww/w.png");
//		
//		File file=new File("F:/workspace-juno/e_trade/src/business/com/gjintel/business/proj/model");
//		File[] list = file.listFiles();
////		for (File f : list) {
////			System.err.println(f.getName());
////		}
//		List<File> subsList=new ArrayList<File>();
//		subsList.add(new File("F:/workspace-juno/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/e_trade/file_resource/project/4028848656fd6e570156fd7282830004.doc"));
//		subsList.add(new File("F:/workspace-juno/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/e_trade/file_resource/project/4028848656fd76c60156fd7d830e0004.doc"));
//		subsList.add(new File("F:/workspace-juno/.metadata/.plugins/org.eclipse.wst.server.core/tmp1/wtpwebapps/e_trade/file_resource/project/4028848656fd76c6015711904d600009.doc"));
//		subsList.add(new File("g:/ww/4028848656fd76c6015711904d600009.doc"));
//		subsList.add(new File("g:/ww/w.png"));
//		
//		List<String> fileNameList=new ArrayList<String>();;
//		fileNameList.add("wei1.jpg");
//		fileNameList.add("wggei1.jpg");
//		fileNameList.add("wesdi1.jpg");
//		fileNameList.add("竞价文件.doc");
//		fileNameList.add("竞价文件.doc");
//		zipFile(subsList, fileNameList, "", zos);
//		zos.flush();
//		zos.close();
		
//		List<String> list = new ArrayList<String>();
//		list.add("草莓"); // 向列表中添加数据
//		list.add("香蕉"); // 向列表中添加数据
//		list.add("菠萝"); // 向列表中添加数据
//		for (int i = 0; i < list.size(); i++) { // 通过循环输出列表中的内容
//			System.out.println(i + ":" + list.get(i));
//		}
//		String o = "草莓";
//		System.out.println("list对象中是否包含元素" + o + ":" + list.contains(o));
		
		List<File> f=new ArrayList<File>();
		f.add(new File("g:/投标人员1.zip"));
		f.add(new File("g:/投标人员2.zip"));
		f.add(new File("g:/投标人员3.zip"));
		
		List<String> nameList=new ArrayList<String>();
		nameList.addAll(Arrays.asList("ww.zip","ww.zip","ww.zip"));
		
		ZipArchiveOutputStream zos=null;
		try {
			zos = new ZipArchiveOutputStream(new FileOutputStream(new File("D:\\test2.zip")));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		BatchZipDownload util=new BatchZipDownload();
		util.zip(f,nameList,"",zos);
		
		
		System.err.println("success!");
		
		System.err.println("BatchDownload.main()");
	}
	
}
